import React, { Component } from 'react';
import { Table, Button, Modal, Form, Input, message } from 'antd';
import axios from 'axios';
import '../mock/table.js'

export default class Tables extends Component {
    constructor(props) {
        super(props);
        this.state = {
            tableData: [],
            pageNo: 1,
            pageSize: 10,
            total: 0,
            view: false,
            tView: false,
            update: false,
            columns: [
                {
                    title: '序号',
                    width: 80,
                    render: (text, record, index) => `${index + 1}`
                },
                {
                    title: '姓名',
                    dataIndex: 'name'
                },
                {
                    title: '年龄',
                    dataIndex: 'age',
                },
                {
                    title: '地址',
                    dataIndex: 'address',
                },
                {
                    title: '编辑',
                    dataIndex: '编辑',
                    render: (text, record, index) => <div className="doing"><span onClick={() => this.edit(0, record)}>详情</span> | <span onClick={() => this.edit(1, record)}>编辑</span> | <span onClick={() => this.edit(2, record)}>删除</span></div>
                }
            ]
        }
    }

    //引用（Refs）提供了一个获得DOM节点或者创建在render方法中的React元素的方法
    formRef = React.createRef()
    key = ''
    edit = (e, text) => {
        switch (e) {
            case 0: this.view(text); break;
            case 1: this.editList(text); break;
            case 2: this.deletes(text); break;
            case 3: this.handleOk(); break;
        }
    }

    view = (e) => {
        this.setState({ tView: true, view: true });
        setTimeout(() => {
            this.formRef.current.setFieldsValue(e);
        }, 500);
    }

    editList = (e) => {
        this.setState({view: true, update: true});
        setTimeout(() => {
            this.formRef.current.resetFields();
            this.formRef.current.setFieldsValue(e);
            this.key = e.key;
        }, 500);
    }
    
    tableChange = (page, size) => {
        this.state.pageNo = page;
        this.state.pageSize = size;
        this.getData();
    }

    getData = (obj) => {
        let param = {
            pageNo: this.state.pageNo - 1,
            pageSize: this.state.pageSize,
            ...obj
        };
        if (obj) {
            param.pageNo = 0;
            param.pageSize = 10;
        }
        axios.post('/table/list', param)
            .then((res) => {
                this.setState({ total: res.data.total });
                this.setState({ tableData: res.data.data });
            }).catch(() => {

            });
    }

    showModal = () => {
        this.setState({ view: true })
    }

    deletes = (es) => {
        this.state.tableData.forEach((e, index) => {
            if(e.key == es.key){
                this.state.tableData.splice(index, 1)
                let obj = [...this.state.tableData];
                this.setState({tableData: obj})
            }
        });
        message.success('删除成功')
    }

    handleOk = () => {
        if (!this.state.tView && !this.state.update) {
            this.formRef.current.validateFields().then(values => {
                this.formRef.current.resetFields();
                this.formRef.current.setFieldsValue(values);
                values.key = Date.parse(new Date());
                this.setState({ tableData: [values, ...this.state.tableData] });
                this.handleCancel();
                message.success('新增成功');
            }).catch(info => {
                console.log('校验失败:', info);
            });
        } else if(this.state.update){
            let obj = this.formRef.current.getFieldsValue();
            this.formRef.current.validateFields().then(values => {
                console.log(values, this.formRef.current)
                this.state.tableData = this.state.tableData.map(e => e.key == this.key?obj:e);
                this.setState({tableData: this.state.tableData})
                message.success('修改成功');
            }).catch(info => {
                console.log('校验失败:', info);
            });
        }
        this.handleCancel();
    }

    handleCancel = () => {
        this.setState({ view: false, tView: false, update: false});
        this.formRef.current.resetFields();
    }

    componentDidMount() {
        let p = async ()=> {
            await console.log("fdf");
        };
        console.log(p().then(
            console.log('bb')
        ));
        this.getData();
    }
    render() {
        return (
            <div>
                <div className="table-btn">
                    <Button type="primary" onClick={() => this.edit(3)}>新增</Button>
                    <Button className="btn-left">批量删除</Button>
                </div>
                <Table
                    columns={this.state.columns}
                    scroll={{ y: '322px' }}
                    pagination={
                        {
                            current: this.state.pageNo,
                            total: this.state.total,
                            onChange: this.tableChange
                        }
                    }
                    dataSource={this.state.tableData}>
                </Table>
                <Modal
                    title="Basic Modal"
                    visible={this.state.view}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}>
                    <Form ref={this.formRef}>
                        <Form.Item
                            label="姓名"
                            name="name"
                            rules={[{ required: true, message: 'Please input your username!' }]}
                        >
                            <Input disabled={this.state.tView} />
                        </Form.Item>
                        <Form.Item
                            label="年龄"
                            name="age"
                            rules={[{ required: true, message: 'Please input your age!' }]}
                        >
                            <Input type="number" disabled={this.state.tView} />
                        </Form.Item>
                        <Form.Item
                            label="地址"
                            name="address"
                            rules={[{ required: true, message: 'Please input your address!' }]}
                        >
                            <Input disabled={this.state.tView} />
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        )
    }
}
